This page has been superceded by a wiki version of this example: SimpleTemplateExample



/*



    File:    template_d077.d

    Author:  J C Calvarese, http://jcc_7.tripod.com/d/

    Date:    2004/01/03

    Purpose: demonstrates using templates in D (using syntax introduced in DMD 0.77)

    

*/



template TStat(T)

{ 

    

    T avg(T a, T b)

    { 

        return (a + b) / 2;

    }

    

    T avg(T a[])

    {

        T b;

        b = 0;  /* If b isn't initialized, then "nan" will be returned. */

        

        for (int i = 0; i < a.length; i++) 
          b += a[i];
        
        return b / a.length;

    }

}





void main()

{  

    int i, j, avg1, avg2;

    int m[];    

    double avg3, avg4;

    double d, e;

    double n[];



    

    i = 6;

    j = 8;

    

    m.length = 4;

    m[0] = 2;

    m[1] = 3;

    m[2] = 4;

    m[3] = 3;

    

    avg1 = TStat!(int).avg(i, j);

    avg2 = TStat!(int).avg(m[]);



    printf("avg1: %d\navg2: %d\n", avg1, avg2);

    

    d = 7.75;

    e = 7.50;

    

    n.length = 3;

    n[0] = 3.13;

    n[1] = 3.15;

    n[2] = 3.19;

    

    avg3 = TStat!(double).avg(d, e);

    avg4 = TStat!(double).avg(n[]);

        

    printf("avg3: %lf\navg4: %lf\n", avg3, avg4);

}